﻿package com.sonishpere 
{
	import com.saint.bitmapDistortion.events.ImageAnimatorEvent;
	import com.saint.bitmapDistortion.StretchyImage;
	import com.saint.bitmapDistortion.StretchyImageAnimator;
	import com.sonishpere.data.Countrys;
	import com.sonishpere.events.BlackHoleEvent;
	import com.saint.utils.Logger;
	import com.sonishpere.events.CountryButtonClickEvent;
	import flash.display.DisplayObject;
	import flash.display.Stage;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	
	/**
	 * ...
	 * @author kembera
	 */
	public class BlackHoleManager extends EventDispatcher
	{
		
		private var _target:DisplayObject;
		private var stage:Stage;
		private var stretchyImage:StretchyImage;		
		private var collapsed:Boolean = false; 		
		private var targetPoint:Point;
		private var stretchyAnimator:StretchyImageAnimator;
		
		public var dissapearingPoint:Point = new Point(0, 0);
		
		private var countryToNavigateTo:String;
		
		public function BlackHoleManager(target:DisplayObject,stage:Stage) 
		{
			Logger.info("BlackHoleManager");
			
			/* add event listeners */
			//target.addEventListener(BlackHoleEvent.COLLAPSE, onContentCollapse);
			target.addEventListener(CountryButtonClickEvent.CLICK, onCountryClick)
			this.stage = stage;
			_target = target;
			
		}
		
		private function onCountryClick(e:CountryButtonClickEvent):void 
		{
			countryToNavigateTo = e.country;
			onContentCollapse(null);
		}
		
		public function onContentCollapse(e:Event):void 
		{
			Logger.info("BlackHoleManager.onContentCollapse");
			
			if (!collapsed)
			{
				
				/* create the image stretchy image to be animated */
				collapsed = true;
				stretchyImage = new StretchyImage(_target, 7, 7);
				stretchyImage.x = _target.x - 18;
				stretchyImage.y = _target.y -18;
				stage.addChild(DisplayObject(stretchyImage));
				stretchyImage.init();
				
				
				/* stretchy Image animation */
				stretchyAnimator = new StretchyImageAnimator();					
				
				targetPoint = dissapearingPoint;;
				//targetPoint = new Point(250,298);
				stretchyAnimator.animateImage(stretchyImage, StretchyImageAnimator.SUCK_TO_POINT, { point:targetPoint, time:2.5 } );
				stretchyAnimator.addEventListener(ImageAnimatorEvent.ANIMATION_COMPLETE, onContentCollapseComplete, false, 0, true);
				_target.visible = false;
			}
			
		}
		
		private function onContentCollapseComplete(e:ImageAnimatorEvent):void 
		{
			dispatchEvent(new BlackHoleEvent(BlackHoleEvent.COLLAPSE_COMPLETE, countryToNavigateTo));
		}
		
	}
	
}